Activity 的启动流程源码分析(Android 9.0)
本篇的源码分析基于
Android 9 ,targetSdkVersion 为28
首先,分析启动流程就要先找到源头,也就是程序的入口,Android启动流程的入口就在 ActivityThread
的 main
方法中,简短的贴下,省略的一些代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 public static void main (String[] args) { Looper.prepareMainLooper(); ActivityThread thread = new ActivityThread(); thread.attach(false , startSeq); if (sMainThreadHandler == null ) { sMainThreadHandler = thread.getHandler(); } if (false ) { Looper.myLooper().setMessageLogging(new LogPrinter(Log.DEBUG, "ActivityThread" )); } Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); Looper.loop(); throw new RuntimeException("Main thread loop unexpectedly exited" ); }
在main方法中使用了 Handler
消息机制,开启了一个主线程的消息循环,然后在这里面直接创建了 ActivityThread
对象,并进行了 attach
操作。看一下 attach
方法到底关联了什么。
1 2 3 4 5 6 7 8 9 10 private void attach (boolean system, long startSeq) { final IActivityManager mgr = ActivityManager.getService(); try { mgr.attachApplication(mAppThread, startSeq); } catch (RemoteException ex) { throw ex.rethrowFromSystemServer(); } }
来到 ActivityManager
中看下 getService()
方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 public static IActivityManager getService () { return IActivityManagerSingleton.get(); } private static final Singleton<IActivityManager> IActivityManagerSingleton = new Singleton<IActivityManager>() { @Override protected IActivityManager create () { final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE); final IActivityManager am = IActivityManager.Stub.asInterface(b); return am; } };
继续回到 attach
方法中,我们知道了是在 ActivityManagerService
中进行了 attachApplication
,先来到AMS中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 public class ActivityManagerService extends IActivityManager .Stub { @Override public final void attachApplication (IApplicationThread thread, long startSeq) { synchronized (this ) { int callingPid = Binder.getCallingPid(); final int callingUid = Binder.getCallingUid(); final long origId = Binder.clearCallingIdentity(); attachApplicationLocked(thread, callingPid, callingUid, startSeq); Binder.restoreCallingIdentity(origId); } } }
attachApplicationLocked
方法的第一个参数是 IApplicationThread
,这个类是 ActivityThread
的内部类 ApplicationThread
的父类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 @GuardedBy ("this" )private final boolean attachApplicationLocked (IApplicationThread thread, int pid, int callingUid, long startSeq) { if (app.isolatedEntryPoint != null ) { thread.runIsolatedEntryPoint(app.isolatedEntryPoint,app.isolatedEntryPointArgs); } else if (app.instr != null ) { thread.bindApplication(processName, appInfo, providers, app.instr.mClass, profilerInfo, app.instr.mArguments, app.instr.mWatcher, app.instr.mUiAutomationConnection, testMode, mBinderTransactionTrackingEnabled, enableTrackAllocation, isRestrictedBackupMode || !normalMode, app.persistent, new Configuration(getGlobalConfiguration()), app.compat, getCommonServicesLocked(app.isolated), mCoreSettingsObserver.getCoreSettingsLocked(), buildSerial, isAutofillCompatEnabled); } else { thread.bindApplication(processName, appInfo, providers, null , profilerInfo, null , null , null , testMode, mBinderTransactionTrackingEnabled, enableTrackAllocation, isRestrictedBackupMode || !normalMode, app.persistent, new Configuration(getGlobalConfiguration()), app.compat, getCommonServicesLocked(app.isolated), mCoreSettingsObserver.getCoreSettingsLocked(), buildSerial, isAutofillCompatEnabled); } if (normalMode) { try { if (mStackSupervisor.attachApplicationLocked(app)) { didSomething = true ; } } catch (Exception e) { Slog.wtf(TAG, "Exception thrown launching activities in " + app, e); badApp = true ; } } }
接下来先看 bindApplication
,之后记得回头研究一下 mStackSupervisor.attachApplicationLocked(app)
干了什么
我们知道了 thread
是 ActivityThread
内部类 ApplicationThread
的父类,要去子类中找父类的方法,来到 ApplicationThread
看下 bindApplication
方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 private class ApplicationThread extends IApplicationThread .Stub { public final void bindApplication (String processName, ApplicationInfo appInfo, List<ProviderInfo> providers, ComponentName instrumentationName, ProfilerInfo profilerInfo, Bundle instrumentationArgs, IInstrumentationWatcher instrumentationWatcher, IUiAutomationConnection instrumentationUiConnection, int debugMode, boolean enableBinderTracking, boolean trackAllocation, boolean isRestrictedBackupMode, boolean persistent, Configuration config, CompatibilityInfo compatInfo, Map services, Bundle coreSettings, String buildSerial, boolean autofillCompatibilityEnabled) { AppBindData data = new AppBindData(); data.processName = processName; data.appInfo = appInfo; data.providers = providers; ... sendMessage(H.BIND_APPLICATION, data); } }
通过 Handler
发送消息,要去看一下这个消息是如何处理的,找到 handleMessage
1 2 3 4 5 6 7 8 9 10 11 public void handleMessage (Message msg) { switch (msg.what) { case BIND_APPLICATION: Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication" ); AppBindData data = (AppBindData)msg.obj; handleBindApplication(data); Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); break ; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 private void handleBindApplication (AppBindData data) { ... try { mInstrumentation.onCreate(data.instrumentationArgs); } catch (Exception e) { throw new RuntimeException( "Exception thrown in onCreate() of " + data.instrumentationName + ": " + e.toString(), e); } try { mInstrumentation.callApplicationOnCreate(app); } catch (Exception e) { if (!mInstrumentation.onException(app, e)) { throw new RuntimeException( "Unable to create application " + app.getClass().getName() + ": " + e.toString(), e); } } }
看一下 callApplicationOnCreate
1 2 3 4 5 6 public class Instrumentation { public void callApplicationOnCreate (Application app) { app.onCreate(); } }
至此,Application创建完毕。
好了,现在可以回过头来,补之前的一个坑,现在开始研究一下 mStackSupervisor.attachApplicationLocked(app)
这个方法将走向何方,看下 ActivityStackSupervisor
,见名知意,Activity栈的管理者.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 public class ActivityStackSupervisor extends ConfigurationContainer implements DisplayListener ,RecentTasks .Callbacks { boolean attachApplicationLocked (ProcessRecord app) throws RemoteException { stack.getAllRunningVisibleActivitiesLocked(mTmpActivityList); final ActivityRecord top = stack.topRunningActivityLocked(); final int size = mTmpActivityList.size(); for (int i = 0 ; i < size; i++) { final ActivityRecord activity = mTmpActivityList.get(i); if (activity.app == null && app.uid == activity.info.applicationInfo.uid && processName.equals(activity.processName)) { try { if (realStartActivityLocked(activity, app, top == activity , true )) { didSomething = true ; } } catch (RemoteException e) { Slog.w(TAG, "Exception in new application when starting activity " + top.intent.getComponent().flattenToShortString(), e); throw e; } } } } }
我们来看一看如何真的开启Activity
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 final boolean realStartActivityLocked (ActivityRecord r, ProcessRecord app, boolean andResume, boolean checkConfig) throws RemoteException { final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread, r.appToken); clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent), System.identityHashCode(r), r.info, mergedConfiguration.getGlobalConfiguration(), mergedConfiguration.getOverrideConfiguration(), r.compat, r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle, r.persistentState, results, newIntents, mService.isNextTransitionForward(), profilerInfo)); final ActivityLifecycleItem lifecycleItem; if (andResume) { lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward()); } else { lifecycleItem = PauseActivityItem.obtain(); } clientTransaction.setLifecycleStateRequest(lifecycleItem); mService.getLifecycleManager().scheduleTransaction(clientTransaction); }
进来 ClientLifecycleManager
1 2 3 4 5 6 7 class ClientLifecycleManager { void scheduleTransaction (ClientTransaction transaction) throws RemoteException { final IApplicationThread client = transaction.getClient(); transaction.schedule(); ... } }
go on,找到 ClientTransaction
1 2 3 4 5 private IApplicationThread mClientpublic void schedule () throws RemoteException { mClient.scheduleTransaction(this ); }
继续继续继续,IApplicationThread
这里又回到了 ActivityThread
1 2 3 4 @Override public void scheduleTransaction (ClientTransaction transaction) throws RemoteException { ActivityThread.this .scheduleTransaction(transaction); }
ActivityThread
继承了 ClientTransactionHandler
,所以上面的方法又进入了这里
1 2 3 4 5 6 7 8 9 10 public abstract class ClientTransactionHandler { void scheduleTransaction (ClientTransaction transaction) { transaction.preExecute(this ); sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction); } }
继续看 handleMessage
方法怎么处理的
1 2 3 4 5 6 7 8 9 10 11 public void handleMessage (Message msg) { switch (msg.what) { case EXECUTE_TRANSACTION: final ClientTransaction transaction = (ClientTransaction) msg.obj; mTransactionExecutor.execute(transaction); ... break ; } }
进来 TransactionExecutor
看一下如何执行的
1 2 3 4 5 6 7 8 9 10 11 public void execute (ClientTransaction transaction) { final IBinder token = transaction.getActivityToken(); log("Start resolving transaction for client: " + mTransactionHandler + ", token: " + token); executeCallbacks(transaction); executeLifecycleState(transaction); mPendingActions.clear(); log("End resolving transaction" ); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 @VisibleForTesting public void executeCallbacks (ClientTransaction transaction) { final List<ClientTransactionItem> callbacks = transaction.getCallbacks(); ... final int size = callbacks.size(); for (int i = 0 ; i < size; ++i) { final ClientTransactionItem item = callbacks.get(i); log("Resolving callback: " + item); final int postExecutionState = item.getPostExecutionState(); final int closestPreExecutionState = mHelper.getClosestPreExecutionState(r, item.getPostExecutionState()); item.execute(mTransactionHandler, token, mPendingActions); item.postExecute(mTransactionHandler, token, mPendingActions); if (r == null ) { r = mTransactionHandler.getActivityClient(token); } } }
进来 LaunchActivityItem
看一下 execute
1 2 3 4 5 6 7 8 9 10 11 12 @Override public void execute (ClientTransactionHandler client, IBinder token, PendingTransactionActions pendingActions) { ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo, mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState, mPendingResults, mPendingNewIntents, mIsForward, mProfilerInfo, client); client.handleLaunchActivity(r, pendingActions, null ); }
再次回到 ActivityThread
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 @Override public Activity handleLaunchActivity (ActivityClientRecord r, PendingTransactionActions pendingActions, Intent customIntent) { ... final Activity a = performLaunchActivity(r, customIntent); ... } private Activity performLaunchActivity (ActivityClientRecord r, Intent customIntent) { ... if (r.isPersistable()) { mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState); } else { mInstrumentation.callActivityOnCreate(activity, r.state); } ... }
进来 Instrumentation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 public void callActivityOnCreate (Activity activity, Bundle icicle) { prePerformCreate(activity); activity.performCreate(icicle); postPerformCreate(activity); }
最后的最后来到 Activity
中
1 2 3 4 5 6 7 8 9 10 11 final void performCreate (Bundle icicle, PersistableBundle persistentState) { mCanEnterPictureInPicture = true ; restoreHasCurrentPermissionRequest(icicle); if (persistentState != null ) { onCreate(icicle, persistentState); } else { onCreate(icicle); } ... }
到这里,从 main
方法走到 Activity
的 onCreate
方法,Activity算是启动了。
好像还有个分支的坑差点忘了填,回想一下 TransactionExecutor
的 execute
方法,我们解释了 executeCallbacks
方法,还差一个 executeLifecycleState
方法没说,这个方法见名知意,感觉像是处理生命周期状态的。具体来看下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 private void executeLifecycleState (ClientTransaction transaction) { final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest(); if (lifecycleItem == null ) { return ; } log("Resolving lifecycle state: " + lifecycleItem); lifecycleItem.execute(mTransactionHandler, token, mPendingActions); lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions); }
来看下 ResumeActivityItem
1 2 3 4 5 6 7 8 9 @Override public void execute (ClientTransactionHandler client, IBinder token, PendingTransactionActions pendingActions) { Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityResume" ); client.handleResumeActivity(token, true , mIsForward, "RESUME_ACTIVITY" ); Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER); }
handleResumeActivity
会执行到 performResumeActivity
最终会走到 Activity
的生命周期方法 onResume
。
高版本的源码的差别还是比较大的,其中涉及的比较重要的类
ActivityThread
ActivityManagerService
Instrumentation
ActivityStackSupervisor
TransactionExecutor
等等
The End
2019-11-26 22:02:45
_kayce